package com.demo.controller.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.demo.common.model.Article;
import com.demo.common.model.ArticleCategory;
import com.demo.common.model.ArticleTag;
import com.demo.common.model.Category;
import com.demo.common.model.Tag;
import com.demo.controller.BaseController;
import com.demo.interceptor.AdminUserInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 
 * @author Emode
 * 文章管理
 */

@Before(AdminUserInterceptor.class)
public class ArticleAdminController extends BaseController<Article>{
	public void index(){
		Page<Article> page = Article.me.paginate(getParaToInt("page",1), 10,getQueryParam());
		List<Article> atList = page.getList();
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		for(Article at :atList){
			Map<String, Object> entry = new HashMap<String, Object>();
			entry.put("id", at.get("id"));
			entry.put("title", at.get("title"));
			entry.put("update_date", at.get("update_date"));
			entry.put("status", at.get("status"));
			entry.put("deleted", at.get("deleted"));
			entry.put("read_count", at.get("read_count"));
			//查询  类别集合
			entry.put("categories", Article.me.getCategories(at));
			//查询标签集合
			entry.put("tags",  Article.me.getTags(at));
			result.add(entry);
		}
		renderJson(new Page(result, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow()));
	}
	
	public void toEdit(){
		String id = getPara("id");
		Article article = Article.me.findById(id);
		setAttr("article", article);
		setAttr("categories", Article.me.getCategories(article));
		setAttr("tags", Article.me.getTags(article));
		setAttr("tagList", Tag.me.getTagList());
		setAttr("cateList", Category.me.getCateList());
		render("/admin/article/article-edit.html");
	}
	//更新文章
	public void update(){
		getCurrentUser().getId();
		Record article = new Record();
		String id = getPara("id");
		String title = getPara("title");
		String cate = getPara("cate");
		String image_url = getPara("image_url");
		Integer status = getParaToInt("status");
		boolean is_deleted = true;
		boolean is_top = false;
		if(status==2){       //置顶时
			is_top = true;
		}else if(status==0){  //保存为草稿时
			is_deleted = false;
		}
		String content = getPara("content");
		String[] tags = getParaValues("tags");
		article.set("title", title)
				.set("content", content)
				.set("status", status)
				.set("is_top",is_top)
				.set("deleted", is_deleted)
				.set("update_date",new Date())
				.set("id", id)
				.set("image_url", image_url);
		Db.update("t_article", article);
		/**
		 * 先删除关联  在重新建立关联
		 */
	    //Article article = Article.me.findById(ids[i]);
		Boolean bool = false;
		List<ArticleCategory> aclist = ArticleCategory.me.getAllById("article_id",article.get("id").toString());
		for(ArticleCategory ac:aclist){
		  bool = ac.delete();
		}
		List<ArticleTag> atlist = ArticleTag.me.getAllById("article_id",article.get("id").toString());
		for(ArticleTag at:atlist){
			bool = at.delete();
		}
		 //bool = article.delete();
		//一对一关联
		Record article_category = new Record();
		article_category.set("article_id", article.get("id"))
						.set("category_id", cate);
		bool = Db.save("t_article_category", article_category);
		//一对多关联
		if (tags != null && tags.length > 0) {
			for (int i = 0; i < tags.length; i++) {
				Record article_tag = new Record();
				article_tag.set("tag_id", Integer.parseInt(tags[i])).set("article_id",  article.get("id"));
				Db.save("t_article_tag", article_tag);
			}

		}
		if(bool){
			success("保存成功");
		}else{
			error("保存失败");
		}
	}
	
	//保存文章
	@Before(Tx.class)
	public void save(){
		getCurrentUser().getId();
		Record article = new Record();
		String title = getPara("title");
		String cate = getPara("cate");
		String image_url = getPara("image_url");
		Integer status = getParaToInt("status");
		boolean is_deleted = true;
		boolean is_top = false;
		if(status==2){       //置顶时
			is_top = true;
		}else if(status==0){  //保存为草稿时
			is_deleted = false;
		}
		String content = getPara("content");
		String[] tags = getParaValues("tags");
		article.set("title", title)
				.set("content", content)
				.set("status", status)
				.set("is_top",is_top)
				.set("deleted", is_deleted)
				.set("read_count", 0)
				.set("create_date",new Date())
				.set("update_date",new Date())
				.set("image_url", image_url);
		Db.save("t_article", article);
		//一对一关联
		Record article_category = new Record();
		article_category.set("article_id", article.get("id"))
						.set("category_id", cate);
		boolean bool = Db.save("t_article_category", article_category);
		//一对多关联
		if (tags != null && tags.length > 0) {
			for (int i = 0; i < tags.length; i++) {
				Record article_tag = new Record();
				article_tag.set("tag_id", Integer.parseInt(tags[i])).set("article_id",  article.get("id"));
				Db.save("t_article_tag", article_tag);
			}

		}
		
		if(bool){
			success("保存成功");
		}else{
			error("保存失败");
		}
	}
	//批量删除
	@Before(Tx.class)
	public void batchDel(){
		String[] ids = getPara("ids").split(",");
		Boolean bool = false;
		if (ids != null && ids.length > 0) {
			for (int i = 0; i < ids.length; i++) {
				 Article article = Article.me.findById(ids[i]);
				 List<ArticleCategory> aclist = ArticleCategory.me.getAllById("article_id",article.get("id").toString());
				 for(ArticleCategory ac:aclist){
					 bool = ac.delete();
				 }
				 List<ArticleTag> atlist = ArticleTag.me.getAllById("article_id",article.get("id").toString());
				 for(ArticleTag at:atlist){
					 bool = at.delete();
				 }
				 bool = article.delete();
			}

		}
		if (bool) {
			success("操作成功");
		} else {
			error("操作失败");
		}

	}
	//操作
	//是否禁用
	public void operate() {
		String type = getPara("type");
		Boolean b;
		Article article =  Article.me.findById(getPara("id"));
		if ("yes".equals(type)) {  //确认发布时
			article.set("status", 1);
			b = true;
		} else {
			b = false;
		}
		
		Boolean bool = article.set("deleted", b).update();
		if (bool) {
			success("操作成功");
		} else {
			error("操作失败");
		}
	}
	
	

}
